<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :destroyOnClose="true"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 采购单基本信息 -->
      <a-card :bordered="false" title="采购单基本信息" style="margin-bottom: 16px">
        <a-descriptions bordered :column="3" size="small">
          <a-descriptions-item label="采购单号">{{ purchaseOrder.purchaseNo }}</a-descriptions-item>
          <a-descriptions-item label="预计到货日期">{{ purchaseOrder.expectedArrivalDate }}</a-descriptions-item>
          <a-descriptions-item label="总金额">¥{{ purchaseOrder.totalAmount ? parseFloat(purchaseOrder.totalAmount).toFixed(2) : '0.00' }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(purchaseOrder.status)">
              <j-dict-tag v-if="purchaseOrder.status" :value="purchaseOrder.status" dictCode="purchase_order_status" />
              <span v-else>-</span>
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="备注">{{ purchaseOrder.remark || '-' }}</a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 到货历史记录 -->
      <a-card v-if="arrivalHistory.length > 0" :bordered="false" title="到货历史记录" style="margin-bottom: 16px">
        <a-timeline>
          <a-timeline-item v-for="(history, index) in arrivalHistory" :key="index" :color="getTimelineColor(index)">
            <p><strong>到货日期：{{ history.arrivalDate }}</strong></p>
            <p>操作人：{{ history.createBy }}</p>
            <p>到货物料：
              <a-tag v-for="detail in history.details" :key="detail.materialId" color="blue">
                {{ detail.materialName }}({{ detail.arrivalQuantity }}{{ detail.unit }})
              </a-tag>
            </p>
          </a-timeline-item>
        </a-timeline>
      </a-card>

      <!-- 到货信息和质检不合格信息 -->
      <a-card :bordered="false" title="到货信息和质检不合格信息">
      <a-form :form="form">
          <!-- 到货日期 -->
          <a-form-item label="到货日期" :labelCol="{ span: 4 }" :wrapperCol="{ span: 8 }">
            <a-date-picker
              v-decorator="['arrivalDate', { rules: [{ required: true, message: '请选择到货日期' }] }]"
              style="width: 100%"
              format="YYYY-MM-DD"
              />
            </a-form-item>

          <!-- 明细表格 -->
          <a-table
            :columns="columns"
            :dataSource="detailList"
            :pagination="false"
            :rowKey="record => record.id"
            bordered
            size="middle"
            :scroll="{ x: 1700 }"
          >
            <!-- 物料图片 -->
            <template slot="materialImageSlot" slot-scope="text">
              <img v-if="text" :src="getImageUrl(text)" alt="物料图片" style="max-width: 50px; max-height: 50px;" 
                   @click="handlePreviewImage(text)" @error="handleImageError" class="material-image" />
              <span v-else>-</span>
            </template>

            <!-- 已到货数量 -->
            <template slot="receivedQuantitySlot" slot-scope="text">
              <span :style="{ color: text > 0 ? '#1890ff' : '' }">{{ text || 0 }}</span>
            </template>

            <!-- 剩余可到货数量 -->
            <template slot="remainingQuantitySlot" slot-scope="text">
              <span :style="{ color: text <= 0 ? '#ff4d4f' : '#52c41a' }">{{ text }}</span>
            </template>

            <!-- 到货数量输入框 -->
            <template slot="arrivalQuantitySlot" slot-scope="text, record, index">
              <a-input-number
                v-model="detailList[index].arrivalQuantity"
                :min="0"
                :max="getRemainingQuantity(record)"
                style="width: 100%"
                placeholder="请输入到货数量"
                @change="(value) => handleArrivalQuantityChange(value, index)"
              />
            </template>

            <!-- 质检不合格数量 -->
            <template slot="unqualifiedQuantitySlot" slot-scope="text, record, index">
              <a-input-number
                v-model="detailList[index].unqualifiedQuantity"
                :min="0"
                :max="detailList[index].arrivalQuantity || 0"
                style="width: 100%"
                placeholder="不合格数量"
                @change="(value) => handleUnqualifiedQuantityChange(value, index)"
              />
            </template>

            <!-- 备注输入框 -->
            <template slot="remarkSlot" slot-scope="text, record, index">
              <a-input
                v-model="detailList[index].remark"
                placeholder="请输入备注"
              />
            </template>
            
            <!-- 凭证上传 -->
            <template slot="evidenceSlot" slot-scope="text, record, index">
              <j-image-upload
                v-model="detailList[index].evidence"
                :number="3"
                :isMultiple="true"
                bizPath="purchase/arrival"
                :returnUrl="true"
                accept=".jpg,.jpeg,.png,.gif"
                :beforeUpload="beforeUpload"
              />
            </template>
          </a-table>

          <!-- 不合格物料列表 -->
          <div v-if="unqualifiedList.length > 0" style="margin-top: 20px;">
            <h3>不合格物料列表</h3>
            <a-table
              :columns="unqualifiedColumns"
              :dataSource="unqualifiedList"
              :pagination="false"
              :rowKey="record => record.id"
              bordered
              size="middle"
            >
              <!-- 物料图片 -->
              <template slot="materialImageSlot" slot-scope="text">
                <img v-if="text" :src="getImageUrl(text)" alt="物料图片" style="max-width: 50px; max-height: 50px;" 
                     @click="handlePreviewImage(text)" @error="handleImageError" class="material-image" />
                <span v-else>-</span>
              </template>

              <!-- 不合格原因 -->
              <template slot="reasonSlot" slot-scope="text, record, index">
                <a-input
                  v-model="unqualifiedList[index].reason"
                  placeholder="请输入不合格原因"
                />
              </template>

              <!-- 凭证上传 -->
              <template slot="evidenceSlot" slot-scope="text, record, index">
                <j-image-upload
                  v-model="unqualifiedList[index].evidence"
                  :number="3"
                  :isMultiple="true"
                  bizPath="purchase/unqualified"
                  :returnUrl="true"
                  accept=".jpg,.jpeg,.png,.gif"
                  :beforeUpload="beforeUpload"
                />
              </template>
            </a-table>
          </div>
        </a-form>
      </a-card>
    </a-spin>
    
    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import moment from 'moment'
import JDictTag from '@/components/dict/JDictTag'
import { getFileAccessHttpUrl } from '@/api/manage'
import JImageUpload from '@/components/jeecg/JImageUpload'
import { getArrivalHistory, getMaterialArrivalQuantity } from '@/api/wms/purchase'

export default {
  name: 'PurchaseArrivalModal',
  components: {
    JDictTag,
    JImageUpload
  },
  data() {
    return {
      title: '采购到货',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      purchaseOrder: {
        purchaseNo: '',
        expectedArrivalDate: '',
        totalAmount: 0,
        status: '',
        supplierName: '',
        remark: ''
      }, // 采购单信息
      detailList: [], // 采购明细列表
      unqualifiedList: [], // 不合格物料列表
      arrivalHistory: [], // 到货历史记录
      materialArrivalQuantity: {}, // 物料已到货数量 {materialId: receivedQuantity}
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '物料图片',
          dataIndex: 'materialImage',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'materialImageSlot' }
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: 120,
          align: 'center'
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 150,
          align: 'center'
        },
        {
          title: '规格型号',
          dataIndex: 'specification',
          width: 120,
          align: 'center'
        },
        {
          title: '供应商',
          dataIndex: 'supplierName',
          width: 150,
          align: 'center'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80,
          align: 'center'
        },
        {
          title: '采购数量',
          dataIndex: 'quantity',
          width: 100,
          align: 'center'
        },
        {
          title: '已到货数量',
          dataIndex: 'receivedQuantity',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'receivedQuantitySlot' },
          customRender: (text, record) => {
            return this.materialArrivalQuantity[record.materialId] || 0;
          }
        },
        {
          title: '剩余可到货',
          dataIndex: 'remainingQuantity',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'remainingQuantitySlot' },
          customRender: (text, record) => {
            return this.getRemainingQuantity(record);
          }
        },
        {
          title: '到货数量',
          dataIndex: 'arrivalQuantity',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'arrivalQuantitySlot' }
        },
        {
          title: '不合格数量',
          dataIndex: 'unqualifiedQuantity',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'unqualifiedQuantitySlot' }
        },
        {
          title: '合格数量',
          dataIndex: 'qualifiedQuantity',
          width: 120,
          align: 'center',
          customRender: (text, record) => {
            const qualifiedQuantity = record.arrivalQuantity - (record.unqualifiedQuantity || 0);
            return qualifiedQuantity >= 0 ? qualifiedQuantity : 0;
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'remarkSlot' }
        },
        {
          title: '凭证',
          dataIndex: 'evidence',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'evidenceSlot' }
        }
      ],
      unqualifiedColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '物料图片',
          dataIndex: 'materialImage',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'materialImageSlot' }
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: 120,
          align: 'center'
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 150,
          align: 'center'
        },
        {
          title: '不合格数量',
          dataIndex: 'unqualifiedQuantity',
          width: 100,
          align: 'center'
        },
        {
          title: '不合格原因',
          dataIndex: 'reason',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'reasonSlot' }
        },
        {
          title: '凭证',
          dataIndex: 'evidence',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'evidenceSlot' }
        }
      ],
      purchaseOrderId: '', // 当前采购单ID
      previewVisible: false,
      previewImage: '',
    }
  },
  methods: {
    show(purchaseOrderId) {
      this.visible = true
      this.purchaseOrderId = purchaseOrderId
      this.loadData(purchaseOrderId)
      
      // 设置默认到货日期为当前日期
      this.$nextTick(() => {
        this.form.setFieldsValue({
          arrivalDate: moment().format('YYYY-MM-DD')
        })
      })
    },
    loadData(purchaseOrderId) {
      this.confirmLoading = true
      
      // 获取采购单详情
      getAction('/wms/purchase/queryById', { id: purchaseOrderId }).then(res => {
        if (res.success && res.result) {
          // 确保所有必要字段都有值
          this.purchaseOrder = {
            purchaseNo: res.result.purchaseNo || '',
            expectedArrivalDate: res.result.expectedArrivalDate || '',
            totalAmount: res.result.totalAmount || 0,
            status: res.result.status || '',
            supplierName: res.result.supplierName || '',
            remark: res.result.remark || '',
            ...res.result
          }
          
          // 获取采购单明细
          getAction('/wms/purchase/detail/list', { purchaseOrderId }).then(detailRes => {
            if (detailRes.success) {
              // 临时存储明细数据
              const details = detailRes.result || [];
              
              // 获取物料已到货数量
              getMaterialArrivalQuantity(purchaseOrderId).then(quantityRes => {
                if (quantityRes.success) {
                  console.log('获取到的已到货数量数据:', quantityRes.result);
                  this.materialArrivalQuantity = quantityRes.result || {};
                  
                  // 如果没有获取到已到货数量，尝试从到货历史记录中计算
                  if (Object.keys(this.materialArrivalQuantity).length === 0) {
                    this.loadArrivalHistoryAndCalculateQuantities(purchaseOrderId, details);
                  } else {
                    // 直接处理明细数据
                    this.processDetailList(details);
                    
                    // 获取到货历史记录
                    this.loadArrivalHistory(purchaseOrderId);
                  }
                } else {
                  // 获取失败时，尝试从历史记录计算
                  this.loadArrivalHistoryAndCalculateQuantities(purchaseOrderId, details);
                }
              }).catch(() => {
                // 获取失败时，尝试从历史记录计算
                this.loadArrivalHistoryAndCalculateQuantities(purchaseOrderId, details);
              });
            } else {
              this.confirmLoading = false;
            }
          }).catch(() => {
            this.confirmLoading = false;
          });
        } else {
          this.$message.error('获取采购单信息失败');
          this.confirmLoading = false;
        }
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    
    // 加载到货历史记录并计算已到货数量
    loadArrivalHistoryAndCalculateQuantities(purchaseOrderId, details) {
      getArrivalHistory(purchaseOrderId).then(historyRes => {
        if (historyRes.success && historyRes.result && historyRes.result.length > 0) {
          // 从历史记录中计算已到货数量
          const calculatedQuantities = {};
          historyRes.result.forEach(history => {
            if (history.details && history.details.length > 0) {
              history.details.forEach(detail => {
                const materialId = detail.materialId;
                // 使用总到货数量（包括合格和不合格）
                const arrivalQuantity = detail.arrivalQuantity || 0;
                calculatedQuantities[materialId] = (calculatedQuantities[materialId] || 0) + arrivalQuantity;
              });
            }
          });
          
          console.log('从历史记录计算的已到货数量:', calculatedQuantities);
          this.materialArrivalQuantity = calculatedQuantities;
        }
        
        // 处理明细数据
        this.processDetailList(details);
        
        // 设置到货历史记录
        this.arrivalHistory = historyRes.success ? (historyRes.result || []) : [];
        this.confirmLoading = false;
      }).catch(() => {
        this.processDetailList(details);
        this.confirmLoading = false;
      });
    },
    
    // 加载到货历史记录
    loadArrivalHistory(purchaseOrderId) {
      getArrivalHistory(purchaseOrderId).then(historyRes => {
        if (historyRes.success) {
          this.arrivalHistory = historyRes.result || [];
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    
    // 处理明细数据
    processDetailList(details) {
      // 为每个明细项添加到货数量和质检结果字段
      this.detailList = details.map(item => {
        const receivedQuantity = this.materialArrivalQuantity[item.materialId] || 0;
        const remainingQuantity = Math.max(0, item.quantity - receivedQuantity);
        // 默认到货数量设置为剩余可到货数量
        const arrivalQuantity = remainingQuantity > 0 ? remainingQuantity : 0;
        const unqualifiedQuantity = 0; // 默认不合格数量为0
        
        return {
          ...item,
          materialType: item.materialType ? String(item.materialType) : '', // 确保是字符串类型
          receivedQuantity,
          remainingQuantity,
          arrivalQuantity,
          unqualifiedQuantity,
          qualifiedQuantity: arrivalQuantity - unqualifiedQuantity, // 计算合格数量
          remark: '', // 备注默认为空
          evidence: '' // 凭证默认为空
        }
      });
      
      // 过滤掉已经完全到货的物料
      this.detailList = this.detailList.filter(item => item.remainingQuantity > 0);
      
      // 如果所有物料都已经完全到货，显示提示
      if (this.detailList.length === 0) {
        this.$message.warning('该采购单所有物料已全部到货，无需再次到货');
      }
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (err) return
        
        // 检查是否有物料可到货
        if (this.detailList.length === 0) {
          this.$message.warning('该采购单没有可到货的物料')
          return
        }
        
        // 检查到货数量是否有效
        const invalidDetail = this.detailList.find(item => item.arrivalQuantity <= 0)
        if (invalidDetail) {
          this.$message.warning('到货数量必须大于0')
          return
        }
        
        // 检查不合格物料是否填写了原因
        const invalidUnqualified = this.unqualifiedList.find(item => !item.reason || item.reason.trim() === '')
        if (invalidUnqualified) {
          this.$message.warning('请填写不合格物料的原因')
          return
        }
        
        this.confirmLoading = true
        
        // 构建提交数据
        const arrivalData = {
          purchaseOrderId: this.purchaseOrderId,
          arrivalDate: typeof values.arrivalDate === 'string' ? values.arrivalDate : moment(values.arrivalDate).format('YYYY-MM-DD'),
          details: this.detailList.map(item => {
            return {
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType ? String(item.materialType) : '', // 确保是字符串类型
              materialImage: item.materialImage,
              specification: item.specification,
              unit: item.unit,
              quantity: item.quantity,
              arrivalQuantity: item.arrivalQuantity,
              unqualifiedQuantity: item.unqualifiedQuantity || 0,
              qualifiedQuantity: item.qualifiedQuantity || (item.arrivalQuantity - (item.unqualifiedQuantity || 0)), // 添加合格数量
              remark: item.remark,
              supplierId: item.supplierId,
              supplierName: item.supplierName,
              evidence: item.evidence // 添加凭证信息
            }
          }),
          unqualifiedList: this.unqualifiedList.map(item => {
            return {
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType ? String(item.materialType) : '', // 确保是字符串类型
              specification: item.specification, // 添加规格型号
              unit: item.unit, // 添加单位
              unqualifiedQuantity: item.unqualifiedQuantity,
              reason: item.reason,
              evidence: item.evidence,
              supplierId: item.supplierId, // 添加供应商ID
              supplierName: item.supplierName // 添加供应商名称
            }
          })
        }
        
        // 提交到后端
        postAction('/wms/purchase/saveArrival', arrivalData).then(res => {
          this.confirmLoading = false
          if (res.success) {
            this.$message.success('保存成功')
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.error(res.message || '保存失败')
          }
        }).catch(() => {
          this.confirmLoading = false
        })
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleArrivalQuantityChange(value, index) {
      // 可以在这里添加其他逻辑，比如验证数量
      const item = this.detailList[index]
      item.arrivalQuantity = value
      
      // 确保不合格数量不超过到货数量
      if (item.unqualifiedQuantity > value) {
        item.unqualifiedQuantity = value
      }
      
      // 更新合格数量
      item.qualifiedQuantity = value - (item.unqualifiedQuantity || 0)
    },
    // 处理不合格数量变更
    handleUnqualifiedQuantityChange(value, index) {
      const item = this.detailList[index]
      item.unqualifiedQuantity = value
      
      // 更新合格数量
      item.qualifiedQuantity = item.arrivalQuantity - value
      
      // 更新不合格物料列表
      this.updateUnqualifiedList()
    },
    // 更新不合格物料列表
    updateUnqualifiedList() {
      // 清空现有不合格列表
      this.unqualifiedList = []
      
      // 添加不合格数量大于0的物料到不合格列表
      this.detailList.forEach(item => {
        if (item.unqualifiedQuantity && item.unqualifiedQuantity > 0) {
          // 检查是否已存在于不合格列表
          const existingItem = this.unqualifiedList.find(u => u.materialId === item.materialId)
          if (!existingItem) {
            // 添加新项
            this.unqualifiedList.push({
              id: item.id,
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType ? String(item.materialType) : '', // 确保是字符串类型
              materialImage: item.materialImage,
              specification: item.specification, // 添加规格型号
              unit: item.unit, // 添加单位
              unqualifiedQuantity: item.unqualifiedQuantity,
              reason: '',
              evidence: '',
              supplierId: item.supplierId, // 添加供应商ID
              supplierName: item.supplierName // 添加供应商名称
            })
          } else {
            // 更新已有项的数量
            existingItem.unqualifiedQuantity = item.unqualifiedQuantity
          }
        }
      })
    },
    getStatusColor(status) {
      // 审核状态颜色映射
      const statusColorMap = {
        1: 'blue', // 草稿
        2: 'orange', // 待审批
        3: 'green', // 已审批
        4: 'cyan', // 部分入库
        5: 'purple', // 已完成
        6: 'red', // 已取消
        7: 'blue', // 已到货
        8: 'orange', // 部分到货
      }
      return statusColorMap[status] || 'default'
    },
    // 获取图片URL
    getImageUrl(text) {
      if (!text) return '';
      try {
        // 使用jeecg标准的文件访问方式
        return getFileAccessHttpUrl(text);
      } catch (error) {
        console.error('获取文件URL失败:', error);
        return '';
      }
    },
    
    // 上传前验证文件类型
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      if (!isImage) {
        this.$message.error('只能上传图片格式文件!');
      }
      return isImage;
    },
    
    // 预览图片
    handlePreviewImage(text) {
      this.previewImage = this.getImageUrl(text);
      this.previewVisible = true;
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e);
      e.target.src = '';
      e.target.alt = '图片加载失败';
    },
    
    // 获取剩余可到货数量
    getRemainingQuantity(record) {
      const receivedQuantity = this.materialArrivalQuantity[record.materialId] || 0;
      return Math.max(0, record.quantity - receivedQuantity);
    },
    
    // 获取时间线颜色
    getTimelineColor(index) {
      const colors = ['green', 'blue', 'red', 'orange'];
      return colors[index % colors.length];
    }
  }
}
</script> 

<style scoped>
.material-image {
  cursor: pointer;
  transition: all 0.3s;
}
.material-image:hover {
  transform: scale(1.1);
}
</style> 